package cn.edu.hbvtc.qms.web.struts.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.edu.hbvtc.qms.domain.Clazz;
import cn.edu.hbvtc.qms.domain.ClazzArrangement;
import cn.edu.hbvtc.qms.domain.Course;
import cn.edu.hbvtc.qms.domain.Department;
import cn.edu.hbvtc.qms.domain.Major;
import cn.edu.hbvtc.qms.domain.Role;
import cn.edu.hbvtc.qms.domain.Teacher;
import cn.edu.hbvtc.qms.domain.User;
import cn.edu.hbvtc.qms.service.IEvaluationService;
import cn.edu.hbvtc.qms.service.IManagementService;
import cn.edu.hbvtc.qms.web.struts.form.ClazzActionForm;

public class ClazzAction extends AbstractBaseDispatchAction {

	private IManagementService managementService = null;
	private IEvaluationService evaluationService = null;

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	public IEvaluationService getEvaluationService() {
		return evaluationService;
	}

	public void setEvaluationService(IEvaluationService evaluationService) {
		this.evaluationService = evaluationService;
	}

	// 跳转到班级管理列表页面
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 获得当前登录用户
		User user = managementService.findUserByUsername(this.getPrincipal().getUsername());
		Role role = managementService.findRoleByName("DEPT_ADMIN");
		if (user.getRoles().contains(role)) {
			Teacher teacher = managementService.findTeacherByUserId(user.getId());
			
			// 首先找出院系管理员所在院系的专业列表
			List<Major> majorList = managementService.findMajorsOfDept(teacher.getDept());

			// 定义clazzListAll，用来保存所有专业下的班级
			List<Clazz> clazzListAll = new ArrayList<Clazz>();

			// 通过遍历专业列表，找出各专业下的班级信息
			for (Iterator<Major> majorIter = majorList.iterator(); majorIter.hasNext();) {
				Major major = majorIter.next();
				List<Clazz> clazzList = managementService.findClazzsOfMajor(major);
				clazzListAll.addAll(clazzList);
			}
			
			request.setAttribute("clazzList", clazzListAll);
		} else {
			List<Clazz> clazzList = managementService.findClazzs();
			request.setAttribute("clazzList", clazzList);
		}
		return mapping.findForward("list");
	}

	// 跳转到班级添加页面
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		User user = managementService.findUserByUsername(this.getPrincipal().getUsername());
		Role role = managementService.findRoleByName("DEPT_ADMIN");

		// 如果是院系部门管理员，则显示该院系的专业下拉列表
		if (user.getRoles().contains(role)) {
			Teacher teacher = managementService.findTeacherByUserId(user.getId());
			Department dept = teacher.getDept();
			request.setAttribute("dept", dept);

			List<Major> majorList = managementService.findMajorsOfDept(teacher.getDept());
			request.setAttribute("majorList", majorList);

			// 院系所有课程列表
			List<Course> courseListAll = new ArrayList<Course>();

			// 提取出公共课程
			List<Course> generalCourseList = managementService.findCoursesOfType(2);
			courseListAll.addAll(generalCourseList);
			
			// 提取出院系专业课程
			for (Iterator<Major> majorIter = majorList.iterator(); majorIter.hasNext();) {
				Major major = majorIter.next();
				List<Course> courseList = managementService.findCoursesOfMajor(major);
				courseListAll.addAll(courseList);
			}

			request.setAttribute("courseList", courseListAll);
			 			
			// 默认艺术与传媒学院的编码是01，查找艺术与传媒学院的所有教师，放入教师列表中
			Department artDept = managementService.findDepartmentByDeptId("01");
			
			List<Teacher> artTeacherList = new ArrayList<Teacher>();
			if (artDept != null) {
				artTeacherList = managementService.findTeachersOfDept(artDept);
			}

			// 默认机电工程学院的编码是02，查找机电工程学院的所有教师，放入教师列表中
			Department mechDept = managementService.findDepartmentByDeptId("02");
			
			List<Teacher> mechTeacherList = new ArrayList<Teacher>();
			if (mechDept != null) {
				mechTeacherList = managementService.findTeachersOfDept(mechDept);
			}

			// 默认医学院的编码是03，查找医学院的所有教师，放入教师列表中
			Department mediDept = managementService.findDepartmentByDeptId("03");
			
			List<Teacher> mediTeacherList = new ArrayList<Teacher>();
			if (mediDept != null) {
				mediTeacherList = managementService.findTeachersOfDept(mediDept);
			}

			// 默认财经学院的编码是04，查找财经学院的所有教师，放入教师列表中
			Department finaDept = managementService.findDepartmentByDeptId("04");
			
			List<Teacher> finaTeacherList = new ArrayList<Teacher>();
			if (finaDept != null) {
				finaTeacherList = managementService.findTeachersOfDept(finaDept);
			}

			// 默认护理学院的编码是05，查找护理学院的所有教师，放入教师列表中
			Department nurDept = managementService.findDepartmentByDeptId("05");
			
			List<Teacher> nurTeacherList = new ArrayList<Teacher>();
			if (nurDept != null) {
				nurTeacherList = managementService.findTeachersOfDept(nurDept);
			}

			// 默认信息技术学院的编码是06，查找信息技术学院的所有教师（计算机基础），放入教师列表中
			Department comDept = managementService.findDepartmentByDeptId("06");
			
			List<Teacher> comTeacherList = new ArrayList<Teacher>();
			if (comDept != null) {
				comTeacherList = managementService.findTeachersOfDept(comDept);
			}

			// 默认建筑技术学院的编码是07，查找建筑技术学院的所有教师，放入教师列表中
			Department archDept = managementService.findDepartmentByDeptId("07");
			
			List<Teacher> archTeacherList = new ArrayList<Teacher>();
			if (archDept != null) {
				archTeacherList = managementService.findTeachersOfDept(archDept);
			}
			
			// 默认外语学院的编码是09，查找外语学院的所有教师（公共英语），放入到教师列表中
			Department engDept = managementService.findDepartmentByDeptId("09");
			
			List<Teacher> engTeacherList = new ArrayList<Teacher>();
			if (engDept != null) {
				engTeacherList = managementService.findTeachersOfDept(engDept);
			}

			// 默认旅游与酒店管理学院的编码是10，查找旅游与酒店管理学院的所有教师，放入到教师列表中
			Department tralDept = managementService.findDepartmentByDeptId("10");
			
			List<Teacher> tralTeacherList = new ArrayList<Teacher>();
			if (tralDept != null) {
				tralTeacherList = managementService.findTeachersOfDept(tralDept);
			}

			// 默认公共课部的编码是11，查找公共课部的所有教师，放入到教师列表中
			Department generalDept = managementService.findDepartmentByDeptId("11");
			
			List<Teacher> generalTeacherList = new ArrayList<Teacher>();
			if (generalDept != null) {
				generalTeacherList = managementService.findTeachersOfDept(generalDept);
			}
			
			// 添加各部门教师到教师列表
			request.setAttribute("artTeacherList", artTeacherList);
			request.setAttribute("mechTeacherList", mechTeacherList);
			request.setAttribute("mediTeacherList", mediTeacherList);
			request.setAttribute("finaTeacherList", finaTeacherList);
			request.setAttribute("nurTeacherList", nurTeacherList);
			request.setAttribute("comTeacherList", comTeacherList);
			request.setAttribute("archTeacherList", archTeacherList);
			request.setAttribute("engTeacherList", engTeacherList);
			request.setAttribute("tralTeacherList", tralTeacherList);
			request.setAttribute("generalTeacherList", generalTeacherList);

		} else {

			List<Department> deptList = managementService.findDepartments();
			request.setAttribute("deptList", deptList);

			List<Course> courseList = managementService.findCourses();
			request.setAttribute("courseList", courseList);

			List<Teacher> teacherList = managementService.findTeachers();
			request.setAttribute("teacherList", teacherList);

		}

		return mapping.findForward("add");
	}

	// 完成添加操作
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ClazzActionForm caf = (ClazzActionForm) form;

		if (caf.getDeptId() == 0) {
			request.setAttribute("deptIdRequired", "请选择院系！");

			return mapping.findForward("toAdd");
		}

		if (caf.getMajorId() == 0) {
			request.setAttribute("majorIdRequired", "请选择专业！");

			Department dept = managementService.findDepartmentById(caf
					.getDeptId());
			List<Major> majorList = managementService.findMajorsOfDept(dept);
			request.setAttribute("majorList", majorList);

			return mapping.findForward("toAdd");
		}

		if (caf.getClazzId() == null || "".equals(caf.getClazzId())) {
			request.setAttribute("clazzIdRequired", "请输入班级编号！");

			Department dept = managementService.findDepartmentById(caf.getDeptId());
			List<Major> majorList = managementService.findMajorsOfDept(dept);
			request.setAttribute("majorList", majorList);
			caf.setMajorId(caf.getMajorId());

			return mapping.findForward("toAdd");
		} else if (caf.getClazzId().length() != 9){
			request.setAttribute("clazzIdLenthError", "请输入9位字符长度的班级编号！例如：200906201班。");
			
			return mapping.findForward("toAdd");
		} else if (managementService.findClazzByClazzId(caf.getClazzId()) != null) {
			request.setAttribute("clazzExistError", "此班级编号已被注册，请使用其他班级编号！");

			Department dept = managementService.findDepartmentById(caf
					.getDeptId());
			List<Major> majorList = managementService.findMajorsOfDept(dept);
			request.setAttribute("majorList", majorList);
			caf.setMajorId(caf.getMajorId());

			return mapping.findForward("toAdd");
		}

		if (caf.getClazzName() == null || "".equals(caf.getClazzName())) {
			request.setAttribute("clazzNameRequired", "请输入班级名称！");

			Department dept = managementService.findDepartmentById(caf
					.getDeptId());
			List<Major> majorList = managementService.findMajorsOfDept(dept);
			request.setAttribute("majorList", majorList);
			caf.setMajorId(caf.getMajorId());

			return mapping.findForward("toAdd");
		}

		if (caf.getStuNumber() <= 0) {
			request.setAttribute("stuNumberRequired", "请输入班级人数！");

			Department dept = managementService.findDepartmentById(caf
					.getDeptId());
			List<Major> majorList = managementService.findMajorsOfDept(dept);
			request.setAttribute("majorList", majorList);
		}

		if (caf.getCourseIds() == null) {
			request.setAttribute("courseSelectRequired", "请选择班级开设课程！");

			Department dept = managementService.findDepartmentById(caf
					.getDeptId());
			List<Major> majorList = managementService.findMajorsOfDept(dept);
			request.setAttribute("majorList", majorList);
			caf.setMajorId(caf.getMajorId());

			return mapping.findForward("toAdd");
		}

		// 设置班级开设课程
		String[] courseIds = caf.getCourseIds();

		// 设置班级任课教师
		String[] teacherIds = caf.getTeacherIds();

		// 将任课教师下拉菜单中的未设置项去除
		List<String> teacherIdsOfSelectList = new ArrayList<String>();

		for (int i = 0; i < teacherIds.length; i++) {
			if (teacherIds[i].equals("0")) {
				continue;
			} else {
				teacherIdsOfSelectList.add(teacherIds[i]);
			}
		}

		if (teacherIdsOfSelectList.size() != courseIds.length) {
			request.setAttribute("teacherSelectRequired", "请选择任课教师！");

			List<Teacher> teacherList = managementService.findTeachers();
			request.setAttribute("teacherList", teacherList);

			Department dept = managementService.findDepartmentById(caf
					.getDeptId());
			List<Major> majorList = managementService.findMajorsOfDept(dept);
			request.setAttribute("majorList", majorList);
			caf.setMajorId(caf.getMajorId());

			return mapping.findForward("toAdd");
		}

		Clazz clazz = new Clazz();
		PropertyUtils.copyProperties(clazz, caf);

		Major major = managementService.findMajorById(caf.getMajorId());
		clazz.setMajor(major);

		Integer clazz_id = managementService.saveClazz(clazz);
		clazz = managementService.findClazzById(clazz_id.intValue());

		for (int i = 0; i < courseIds.length; i++) {
			Teacher teacher = managementService.findTeacherById(Integer
					.parseInt(teacherIdsOfSelectList.get(i)));
			Course course = managementService.findCourseById(Integer
					.parseInt(courseIds[i]));

			ClazzArrangement clazzArrangement = new ClazzArrangement();
			clazzArrangement.setClazz(clazz);
			clazzArrangement.setCourse(course);
			clazzArrangement.setTeacher(teacher);
			clazzArrangement.setTerm(managementService.findTermOfNow());// 设置当前学期

			evaluationService.saveClazzArrangement(clazzArrangement);
		}

		return mapping.findForward("addSave");
	}

	// 跳转到班级修改页面
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ClazzActionForm caf = (ClazzActionForm) form;
		Clazz clazz = managementService.findClazzById(caf.getId());
		request.setAttribute("clazz", clazz);


		User user = managementService.findUserByUsername(this.getPrincipal().getUsername());
		Role role = managementService.findRoleByName("DEPT_ADMIN");

		// 如果是院系部门管理员，则显示该院系的专业下拉列表
		if (user.getRoles().contains(role)) {
			Teacher teacher = managementService.findTeacherByUserId(user.getId());
			Department dept = teacher.getDept();
			request.setAttribute("dept", dept);

			List<Major> majorList = managementService.findMajorsOfDept(teacher.getDept());
			request.setAttribute("majorList", majorList);

			// 院系所有课程列表
			List<Course> courseListAll = new ArrayList<Course>();

			// 提取出公共课程
			List<Course> generalCourseList = managementService.findCoursesOfType(2);
			courseListAll.addAll(generalCourseList);
			
			// 提取出院系专业课程
			for (Iterator<Major> majorIter = majorList.iterator(); majorIter.hasNext();) {
				Major major = majorIter.next();
				List<Course> courseList = managementService.findCoursesOfMajor(major);
				courseListAll.addAll(courseList);
			}

			request.setAttribute("courseList", courseListAll);
			 			
			// 默认艺术与传媒学院的编码是01，查找艺术与传媒学院的所有教师，放入教师列表中
			Department artDept = managementService.findDepartmentByDeptId("01");
			
			List<Teacher> artTeacherList = new ArrayList<Teacher>();
			if (artDept != null) {
				artTeacherList = managementService.findTeachersOfDept(artDept);
			}

			// 默认机电工程学院的编码是02，查找机电工程学院的所有教师，放入教师列表中
			Department mechDept = managementService.findDepartmentByDeptId("02");
			
			List<Teacher> mechTeacherList = new ArrayList<Teacher>();
			if (mechDept != null) {
				mechTeacherList = managementService.findTeachersOfDept(mechDept);
			}

			// 默认医学院的编码是03，查找医学院的所有教师，放入教师列表中
			Department mediDept = managementService.findDepartmentByDeptId("03");
			
			List<Teacher> mediTeacherList = new ArrayList<Teacher>();
			if (mediDept != null) {
				mediTeacherList = managementService.findTeachersOfDept(mediDept);
			}

			// 默认财经学院的编码是04，查找财经学院的所有教师，放入教师列表中
			Department finaDept = managementService.findDepartmentByDeptId("04");
			
			List<Teacher> finaTeacherList = new ArrayList<Teacher>();
			if (finaDept != null) {
				finaTeacherList = managementService.findTeachersOfDept(finaDept);
			}

			// 默认护理学院的编码是05，查找护理学院的所有教师，放入教师列表中
			Department nurDept = managementService.findDepartmentByDeptId("05");
			
			List<Teacher> nurTeacherList = new ArrayList<Teacher>();
			if (nurDept != null) {
				nurTeacherList = managementService.findTeachersOfDept(nurDept);
			}

			// 默认信息技术学院的编码是06，查找信息技术学院的所有教师（计算机基础），放入教师列表中
			Department comDept = managementService.findDepartmentByDeptId("06");
			
			List<Teacher> comTeacherList = new ArrayList<Teacher>();
			if (comDept != null) {
				comTeacherList = managementService.findTeachersOfDept(comDept);
			}

			// 默认建筑技术学院的编码是07，查找建筑技术学院的所有教师，放入教师列表中
			Department archDept = managementService.findDepartmentByDeptId("07");
			
			List<Teacher> archTeacherList = new ArrayList<Teacher>();
			if (archDept != null) {
				archTeacherList = managementService.findTeachersOfDept(archDept);
			}
			
			// 默认外语学院的编码是09，查找外语学院的所有教师（公共英语），放入到教师列表中
			Department engDept = managementService.findDepartmentByDeptId("09");
			
			List<Teacher> engTeacherList = new ArrayList<Teacher>();
			if (engDept != null) {
				engTeacherList = managementService.findTeachersOfDept(engDept);
			}

			// 默认旅游与酒店管理学院的编码是10，查找旅游与酒店管理学院的所有教师，放入到教师列表中
			Department tralDept = managementService.findDepartmentByDeptId("10");
			
			List<Teacher> tralTeacherList = new ArrayList<Teacher>();
			if (tralDept != null) {
				tralTeacherList = managementService.findTeachersOfDept(tralDept);
			}

			// 默认公共课部的编码是11，查找公共课部的所有教师，放入到教师列表中
			Department generalDept = managementService.findDepartmentByDeptId("11");
			
			List<Teacher> generalTeacherList = new ArrayList<Teacher>();
			if (generalDept != null) {
				generalTeacherList = managementService.findTeachersOfDept(generalDept);
			}
			
			// 添加各部门教师到教师列表
			request.setAttribute("artTeacherList", artTeacherList);
			request.setAttribute("mechTeacherList", mechTeacherList);
			request.setAttribute("mediTeacherList", mediTeacherList);
			request.setAttribute("finaTeacherList", finaTeacherList);
			request.setAttribute("nurTeacherList", nurTeacherList);
			request.setAttribute("comTeacherList", comTeacherList);
			request.setAttribute("archTeacherList", archTeacherList);
			request.setAttribute("engTeacherList", engTeacherList);
			request.setAttribute("tralTeacherList", tralTeacherList);
			request.setAttribute("generalTeacherList", generalTeacherList);

		} else {

			List<Department> deptList = managementService.findDepartments();
			request.setAttribute("deptList", deptList);

			List<Course> courseList = managementService.findCourses();
			request.setAttribute("courseList", courseList);

			List<Teacher> teacherList = managementService.findTeachers();
			request.setAttribute("teacherList", teacherList);

		}

		// 显示该班级所开设课程
		// 更正：修改该班级所开设课程时，清空已设课程，重新设置课程
		// Set<ClazzArrangement> caSet = clazz.getClazzArrangement();
		// if (caSet != null) {
		// String[] courseIds = new String[caSet.size()];
		// int i = 0;
		// for (Iterator<ClazzArrangement> iter = caSet.iterator();
		// iter.hasNext();) {
		// ClazzArrangement ca = iter.next();
		// Course course = ca.getCourse();
		// courseIds[i++] = String.valueOf(course.getId());
		// }
		// caf.setCourseIds(courseIds);
		// }

		return mapping.findForward("update");
	}

	// 完成班级修改
	public ActionForward updateSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ClazzActionForm caf = (ClazzActionForm) form;

		if (caf.getDeptId() == 0) {
			request.setAttribute("deptIdError", "请选择院系！");
			return mapping.findForward("toUpdate");
		}
		if (caf.getMajorId() == 0) {
			request.setAttribute("majorIdError", "请选择专业！");
			return mapping.findForward("toUpdate");
		}

		if (!caf.getClazzId().equals(
				managementService.findClazzById(caf.getId()).getClazzId())) { // 判断提交的院系编号是否被用户修改

			if (caf.getClazzId() == null || "".equals(caf.getClazzId())) {

				request.setAttribute("clazzIdError", "请输入班级编号！");
				return mapping.findForward("toUpdate");
			} else if (managementService.findClazzByClazzId(caf.getClazzId()) != null) {

				request.setAttribute("clazzIdRequest", "该编号已存在，请重新输入！");

				return mapping.findForward("toUpdate");
			}
		}
		if (caf.getClazzName() == null || "".equals(caf.getClazzName())) {

			request.setAttribute("clazzNameError", "请输入班级名称！");

			return mapping.findForward("toUpdate");
		}

		if (caf.getStuNumber() <= 0) {
			request.setAttribute("stuNumberRequired", "请输入班级人数！");

			Department dept = managementService.findDepartmentById(caf
					.getDeptId());
			List<Major> majorList = managementService.findMajorsOfDept(dept);
			request.setAttribute("majorList", majorList);
		}

		if (caf.getCourseIds() == null) {
			request.setAttribute("courseSelectRequired", "请选择该班级开设课程！");

			return mapping.findForward("toUpdate");
		}

		Clazz clazz = managementService.findClazzById(caf.getId());
		PropertyUtils.copyProperties(clazz, caf);

		Major major = managementService.findMajorById(caf.getMajorId());
		clazz.setMajor(major);

		managementService.updateClazz(clazz);

		// 清除该班级本学期的课程安排，重新添加
		List<ClazzArrangement> caList = evaluationService.findClazzArrangementOfClazz(clazz, managementService.findTermOfNow());
		if (caList != null) {
			for (Iterator<ClazzArrangement> iter = caList.iterator(); iter.hasNext();) {
				evaluationService.deleteClazzArrangementById(iter.next().getId());
			}
		}

		// 设置班级开设课程
		String[] courseIds = caf.getCourseIds();

		// 设置班级任课教师
		String[] teacherIds = caf.getTeacherIds();

		// 将任课教师下拉菜单中的未设置项去除
		List<String> teacherIdsOfSelectList = new ArrayList<String>();

		for (int i = 0; i < teacherIds.length; i++) {
			if (teacherIds[i].equals("0")) {
				continue;
			} else {
				teacherIdsOfSelectList.add(teacherIds[i]);
			}
		}

		if (teacherIdsOfSelectList.size() != courseIds.length) {
			request.setAttribute("teacherSelectRequired", "请选择任课教师！");

			List<Teacher> teacherList = managementService.findTeachers();
			request.setAttribute("teacherList", teacherList);

			Department dept = managementService.findDepartmentById(caf
					.getDeptId());
			List<Major> majorList = managementService.findMajorsOfDept(dept);
			request.setAttribute("majorList", majorList);
			caf.setMajorId(caf.getMajorId());

			return mapping.findForward("toUpdate");
		}

		for (int i = 0; i < courseIds.length; i++) {
			Teacher teacher = managementService.findTeacherById(Integer
					.parseInt(teacherIdsOfSelectList.get(i)));
			Course course = managementService.findCourseById(Integer
					.parseInt(courseIds[i]));

			ClazzArrangement clazzArrangement = new ClazzArrangement();
			clazzArrangement.setClazz(clazz);
			clazzArrangement.setCourse(course);
			clazzArrangement.setTeacher(teacher);
			clazzArrangement.setTerm(managementService.findTermOfNow());// 设置当前学期

			evaluationService.saveClazzArrangement(clazzArrangement);
		}

		return mapping.findForward("updateSave");
	}

	// 完成班级删除操作
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ClazzActionForm caf = (ClazzActionForm) form;
		managementService.deleteClazzById(caf.getId());

		return mapping.findForward("delete");
	}

}
